package com.snakegame.ui;

import com.snakegame.core.*;
import com.snakegame.config.*;

import javax.swing.*;
import java.awt.*;

/**
 * 游戏主窗口类，包含游戏的所有UI组件
 */
public class GameFrame extends JFrame {
    private GameManager gameManager;
    private StartMenuPanel startMenuPanel;
    private GamePanel gamePanel;
    private ScoreBoard scoreBoard;
    private GameOverPanel gameOverPanel;
    private MapSelectionPanel mapSelectionPanel;
    private ModeSelectionPanel modeSelectionPanel;
    private DifficultySelectionPanel difficultySelectionPanel;
    
    public GameFrame(GameManager gameManager) {
        this.gameManager = gameManager;
        
        setTitle("贪吃蛇游戏");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setResizable(false);
        
        initComponents();
        setupLayout();
        
        // 注册游戏面板和计分板
        gameManager.setGamePanel(gamePanel);
        gameManager.setScoreBoard(scoreBoard);
    }
    
    private void initComponents() {
        startMenuPanel = new StartMenuPanel(gameManager, this);
        gamePanel = new GamePanel(gameManager, this); // 传递 GameFrame 实例
        scoreBoard = new ScoreBoard(gameManager);
        gameOverPanel = new GameOverPanel(gameManager, this);
        mapSelectionPanel = new MapSelectionPanel(gameManager, this);
        modeSelectionPanel = new ModeSelectionPanel(gameManager, this);
        difficultySelectionPanel = new DifficultySelectionPanel(gameManager, this);
        
        // 添加键盘监听器到游戏面板
        gamePanel.addKeyListener(new GameKeyListener(gameManager));
        gamePanel.setFocusable(true);
    }
    
    private void setupLayout() {
        CardLayout cardLayout = new CardLayout();
        JPanel mainPanel = new JPanel(cardLayout);
        
        mainPanel.add(startMenuPanel, "START_MENU");
        mainPanel.add(gamePanel, "GAME");
        mainPanel.add(gameOverPanel, "GAME_OVER");
        mainPanel.add(mapSelectionPanel, "MAP_SELECTION");
        mainPanel.add(modeSelectionPanel, "MODE_SELECTION");
        mainPanel.add(difficultySelectionPanel, "DIFFICULTY_SELECTION");
        
        add(mainPanel);
        this.mainPanel = mainPanel;
        this.cardLayout = cardLayout;
        
        // 显示开始菜单
        cardLayout.show(mainPanel, "START_MENU");
    }
    
    public void showPanel(String panelName) {
        cardLayout.show(mainPanel, panelName);
        
        // 如果显示游戏面板，请求焦点以便接收键盘事件
        if ("GAME".equals(panelName)) {
            gamePanel.requestFocusInWindow();
        }
    }
    
    private JPanel mainPanel;
    private CardLayout cardLayout;
}    